package net.maxwoods.nimble.websocket;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;

public class WebSocketServer {
    private static final int Port=9501;
    private final IoAcceptor ioAcceptor=new NioSocketAcceptor();

    public void Start()
    {
        ioAcceptor.getFilterChain().addLast("coder",
                new ProtocolCodecFilter(new MinaEncoder(), new MinaDecoder()));
        // 设置消息处理类（创建、关闭Session，可读可写等等，继承自接口IoHandler）
        ioAcceptor.setHandler(new WebSocketHandler());
        // 设置接收缓存区大小
        ioAcceptor.getSessionConfig().setReadBufferSize(2048);
        ioAcceptor.getSessionConfig().setIdleTime(IdleStatus.READER_IDLE,60 * 60 * 2);
        try {
            ioAcceptor.bind(new InetSocketAddress(Port));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop()
    {
        ioAcceptor.unbind();
        ioAcceptor.dispose();
    }
}
